package brad.zimmerman.dungeon.game;

import java.util.Arrays;
import java.util.Random;

import brad.zimmerman.dungeon.game.ActivityDungeons;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class ActivityShop extends Activity{
	ClassBackgroundSound backgroundMusic;
	ClassDatabaseAct database;
	public ClassDrawingHolder Draws = new ClassDrawingHolder();
	public int[] settings;
	public ClassUnlockable unlock;
	boolean unlockAll;
	public ClassGameStats playerStats;
	public Point point;
	public int width,height;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		backgroundMusic = new ClassBackgroundSound(this);
		database = new ClassDatabaseAct(this);
		database.checkCreate();
		settings = database.returnScoreValues(0, -1, -1);
		unlock = new ClassUnlockable(returnLevel());
		unlockAll = false;
		point = new Point(getDisplaySize(getWindowManager().getDefaultDisplay()));
        width = point.x;
    	height = point.y;
    	shopScreen(0);
	}
	
	 @Override
		public void onDestroy(){
			super.onDestroy(); 
			backgroundMusic.stopBackground();
		}
		
	    @Override
		public void onStop(){
			super.onStop(); 
			backgroundMusic.stopBackground();
		}
	    
		@Override
		public void onPause(){
			super.onPause(); 
			backgroundMusic.stopBackground();
		}
		
		@Override
		public void onStart(){
			super.onStart(); 
			if(!backgroundMusic.running){
				backgroundMusic.setBackgoundNoiseTheme();
				backgroundMusic.playBackground();
			}
			settings = database.returnScoreValues(0, -1, -1);
		}
		
		@Override
		public void onResume(){
			super.onResume(); 
			if(!backgroundMusic.running){
				backgroundMusic.setBackgoundNoiseTheme();
				backgroundMusic.playBackground();
			}
			settings = database.returnScoreValues(0, -1, -1);
		}
	
	private static Point getDisplaySize(final Display display) {
	    final Point point = new Point();
	    //try {
	    //    display.getSize(point);
	    //} catch (java.lang.NoSuchMethodError ignore) { // Older device
	        point.x = display.getWidth();
	        point.y = display.getHeight();
	    //}
	    return point;
	}
	
	public static <T> T[] concatenateArrays(T[] first, T[] second) {
		  T[] result = Arrays.copyOf(first, first.length + second.length);
		  System.arraycopy(second, 0, result, first.length, second.length);
		  return result;
		}
	
	public int calculateProgress(int exp){
		int i = 1;
		int lower, higher;
		float percent;
		while(((i*i)*500 + i*500)< exp){
			i++;
		}
		lower = exp - (((i-1)*(i-1))*500 + (i-1)*500);
		higher = ((i*i)*500 + i*500) - (((i-1)*(i-1))*500 + (i-1)*500);
		percent = ((float)lower)/((float)higher);
		return (int) (percent*100);
	}
	
	public int returnLevel(){
		int level=0;
		int count = 0;
		
		for(;level<Draws.levelStrings.length+1;level++){
			for(int place = 0;place<Draws.unlockLevels.length;place++){
				if(Draws.unlockLevels[place] < level){
					//System.out.println(Draws.classStrings[place] + "\nLevel: " + level + "\n");
					if(database.returnCompleted(0
							,place
        				  ,level,database,Draws)){
						//System.out.println("failed\n");
						//return level - 1;
						count++;
					}else{
						//System.out.println("passed\n");
					}
				}
			}
			if(count < returnClassPoints(level)){
				return (level -1) + settings[1];
			}
			count = 0;
		}
        return level + settings[1];
	}
	
	public int returnClassPoints(int level){
		switch(level){
			case 0:return 1;
			case 1:return 3;
			case 2:return 4;
			case 3:return 5;
			case 4:return 6;
			case 5:return 7;
			case 6:return 8;
			case 7:return 9;
			case 8:return 10;
			case 9:return 11;
			case 10:return 12;
			case 11:return 13;
			case 12:return 14;
			case 13:return 15;
			case 14:return 15;
			case 15:return 1;
			default:return 15;
		}
	}
	
	public int returnLevelCount(int level){
		int count = 0;
		for(int place = 0;place<Draws.unlockLevels.length;place++){
			if(Draws.unlockLevels[place] < level){

				if(database.returnCompleted(0
						,place
    				  ,level,database,Draws)){

					count++;
				}
			}
		}
		return returnClassPoints(level) - count;
	}
	
	public int randomNumber(int max){
		Random random = new Random(System.nanoTime());;
		//false means that the odds hit
		return (random.nextInt( max ));
	}
	
	public String[] mixupAdvice(String[] advice){
		Random random = new Random(System.currentTimeMillis());
		String holder = "";
		int switch1,switch2;
		for(int i = 0 ; i < advice.length;i++){
			switch1 = random.nextInt( advice.length );
			switch2 = random.nextInt( advice.length );
			while(switch2==switch1){
				switch2 = random.nextInt( advice.length );
			}
			holder = advice[switch1];
			advice[switch1] = advice[switch2];
			advice[switch2] = holder;
		}
		return advice;
	}
	
	public String returnProgressMarquee(int level){
		int neededClasses = returnLevelCount(level+1);
		String[] advice;
		switch(randomNumber(3)){
			case 0:advice = mixupAdvice(Draws.helpfulTips);break;
			case 1:advice = mixupAdvice(Draws.helpfulTips2);break;
			case 2:advice = mixupAdvice(Draws.helpfulTips3);break;
			default:advice = mixupAdvice(Draws.helpfulTips);break;
		}
		String holder = "";
		holder+="Beat the "+ Draws.levelStrings[level+1] + " level with "+ neededClasses +" more class";
		if (neededClasses>1){
			holder+="es";
		}
		holder+=" to unlock the next tier of characters. \t\t\t";
		
		for (int i = 0; i < advice.length;i++){
			holder+= advice[i];
			holder+="\t\t\t";
		}
		
		return holder;
		
	}
	
	public int calculateLevel(int exp){
		int i = 1;
		while(((i*i)*500 + i*500)< exp){
			i++;
		}
		return i-1;
	}
	
	public String compileEnemyData(int enemy){
		String holder = "";
		
		holder += "Base Health: " + (Draws.enemyBaseStats[enemy][0])*10 + "%\n";
		holder += "Base Attack: " + (Draws.enemyBaseStats[enemy][1])*10 + "%\n";
		if(enemy!=0){
			holder += "Starting Lives: " + Draws.enemyBaseStats[enemy][2] + "\n";
		}else{
			holder += "Starting Lives: Same as level\n";
		}
		
		holder += "\nModifiers\n";
		
		if(Draws.enemyAbilityStats[enemy][0]){holder += "Mana Burn; ";}
		if(Draws.enemyAbilityStats[enemy][1]){holder += "Poison; ";}
		if(Draws.enemyAbilityStats[enemy][2]){holder += "25% Magic Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][3]){holder += "50% Magic Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][4]){holder += "25% Physical Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][5]){holder += "50% Physical Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][6]){holder += "Amnesia; ";}
		if(Draws.enemyAbilityStats[enemy][7]){holder += "Blind; ";}
		if(Draws.enemyAbilityStats[enemy][8]){holder += "Weakness; ";}
		if(Draws.enemyAbilityStats[enemy][9]){holder += "Magical Attack; ";}
		if(Draws.enemyAbilityStats[enemy][10]){holder += "Undead; ";}
		if(Draws.enemyAbilityStats[enemy][11]){holder += "Coward; ";}
		if(Draws.enemyAbilityStats[enemy][12]){holder += "Banish; ";}
		if(Draws.enemyAbilityStats[enemy][13]){holder += "First Strike; ";}
		if(Draws.enemyAbilityStats[enemy][14]){holder += "Static; ";}
		
		return holder;
	}
	
	public String compileRituals(int god){
		String holder = "";
		holder += "Cost " + Draws.ritualLevels[god][0]*10 + " Piety: "+ Draws.ritualDescriptions[god][2] +"\n";
		holder += "Cost " + Draws.ritualLevels[god][1]*10 + " Piety: "+ Draws.ritualDescriptions[god][3] + "\n";
		holder += "Cost " + Draws.ritualLevels[god][2]*10 + " Piety: "+ Draws.ritualDescriptions[god][4] + "\n";
		return holder;
	}
	
	public void shopScreen(int startingPosition){
		
		//System.out.println("ShopScreen");
		if(backgroundMusic.running && backgroundMusic.currentlyPlaying != -1){
			backgroundMusic.stopBackground();
		}
		if(!backgroundMusic.running){
			backgroundMusic.setBackgoundNoiseTheme();
			backgroundMusic.playBackground();
		}
		
		setContentView(R.layout.shopwheel);
        //String[] both = concatenateArrays(Draws.itemSuffixes, Draws.techSuffixes);
        
        final TextView text1 = (TextView) findViewById(R.id.textshopa);
        final TextView text2 = (TextView) findViewById(R.id.textshopb);
        final TextView text3 = (TextView) findViewById(R.id.textshopc);
        final TextView text4 = (TextView) findViewById(R.id.textshopd);
        final TextView marquee1 = (TextView) findViewById(R.id.marqueetextshop);
        
        
        //final RadioGroup Legend = (RadioGroup) findViewById(R.id.radio_groupShop);
        //Legend.check(R.id.radioButtonA);
        
        //final TextView cost = (TextView) findViewById(R.id.textcost);
        //final TextView goldcost = (TextView) findViewById(R.id.textgoldcost);
        //final TextView hpotioncost = (TextView) findViewById(R.id.texthpotioncost);
        //final TextView mpotioncost = (TextView) findViewById(R.id.textmpotioncost);
        
        final TextView shopText = (TextView) findViewById(R.id.shopText);
        //final TextView stock = (TextView) findViewById(R.id.textstock);
        //final TextView goldstock = (TextView) findViewById(R.id.textgoldstock);
        //final TextView hpotionstock = (TextView) findViewById(R.id.texthpotionstock);
        //final TextView mpotionstock = (TextView) findViewById(R.id.textmpotionstock);
        
        final String[] both = concatenateArrays(Draws.itemSuffixes, Draws.techSuffixes);
        final ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar2); 
        final int experience = database.returnTechValues("Knowledge");
        final int max = calculateProgress(experience);
        
        
        marquee1.setSelected(true);
        marquee1.setText(returnProgressMarquee(unlock.getLevel()));
        
        
    	database.InsertTech("Knowledge", experience);
    	
    	progress.setProgress(0);
        
        //text1.setTextSize((scale.getScale()*(float).90));
        //text2.setTextSize(((scale.getScale())*(float).50));
        //text3.setTextSize((scale.getScale()*(float).90));
        //text4.setTextSize(((scale.getScale())*(float).50));
        
        //cost.setText("Upgrade Cost");
        shopText.setText("Current Level: " + calculateLevel(experience));
        //cost.setTextSize((scale*(float).65));
        //shopText.setTextSize(15);
        
        final Gallery g1 = (Gallery) findViewById(R.id.shopgallery);
        g1.setAdapter(new shopImageAdapter(this,R.id.shopgallery,0));
        ((Gallery) findViewById(R.id.shopgallery)).setSelection(startingPosition);
        g1.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
           {
        	  switch(((shopImageAdapter) g1.getAdapter()).returnChoice()){
        	  	case 0:
        		  int techLevel = database.returnTechValues(both[position]);
        		  ClassShop shopping = new ClassShop(techLevel,position+1);
        	  
        		  //System.out.println(techLevel + " " + position + "\n");
        		  if (position < 10){
        		  text1.setText(Draws.itemPrefixes[techLevel] 
        				  + " " + both[position]);
        		  }else{
        		  text1.setText(Draws.techPrefixes[techLevel] 
        				  + " " + both[position]);
        		  }
        		  text2.setText(shopping.printEffectsBuyScreen());
        		  if (techLevel < 9){
            	  shopping = new ClassShop(techLevel+1,position+1);
            	  if (position < 10){
            		  text3.setText("Next Level: " + Draws.itemPrefixes[techLevel+1] + " " + both[position]);
            	  }else{
            		  text3.setText("Next Level: " + Draws.techPrefixes[techLevel+1] + " " + both[position]);
            	  }
            	  text4.setText(shopping.printEffectsBuyScreen());
        		  }else{
            	  text3.setText("Max Level Reached");
            	  text4.setText("");
        		  }
        		  break;
        	  	case 1:
        	  		
        	  		if(!unlockAll){
       	  				text1.setText("Class: " + Draws.classStrings[unlock.convertClassPos(position)]);
       	  				text2.setText(Draws.classDescriptions[unlock.convertClassPos(position)]);
       	  				text3.setText(Draws.classStrings[unlock.convertClassPos(position)] + " Strategy");
       	  				text4.setText(Draws.classStrategies[unlock.convertClassPos(position)]);
       	  			}else{
       	  				text1.setText("Class: " + Draws.classStrings[position]);
       	  				text2.setText(Draws.classDescriptions[position]);
       	  				text3.setText(Draws.classStrings[position] + " Strategy");
       	  				text4.setText(Draws.classStrategies[position]);
       	  			}

        	  	break;
        	  	case 2:
        	  		
        	  		
        	  		if(!unlockAll){
             		  text1.setText("Enemy: " + Draws.enemyStrings[unlock.convertEnemyPos(position)]);
             		  text2.setText(compileEnemyData(unlock.convertEnemyPos(position)));
             		  text3.setText("Strategy Against");
                      text4.setText(Draws.enemyStrategies[unlock.convertEnemyPos(position)]);
             		   
            	   	}else{
            	   		text1.setText("Enemy: " + Draws.enemyStrings[position]);
                    	text2.setText(compileEnemyData(position));
                    	text3.setText("Strategy Against");
                        text4.setText(Draws.enemyStrategies[position]);
            	   	}
        	  	break;
        	  	case 3:
        	  		if(!unlockAll){
        	  			text1.setText("Glyph: " + Draws.glyphStrings[unlock.convertGlyphPos(position)]);
               		  	text2.setText(Draws.glyphDescriptions[unlock.convertGlyphPos(position)]);
               		  	text3.setText("Glyph Strategies");
                        text4.setText(Draws.glyphStrategies[unlock.convertGlyphPos(position)]);
               		   
              	   	}else{
              	   		text1.setText("Glyph: " + Draws.convertedGlyphNames[position]);
              	   		text2.setText(Draws.convertedGlyphDescriptions[position]);
              	   		text3.setText("Glyph Strategies");
              	   		text4.setText(Draws.convertedGlyphStrategies[position]);
              	   	}
        	  	break;
        	  	case 4:
        	  			text1.setText("God: " + Draws.godNames[position]);
        	  			text2.setText(Draws.godDescriptions[position] + "\nBlessing: "+Draws.ritualDescriptions[position][0] +
        	  					"\nCurse: "+Draws.ritualDescriptions[position][1]);
        	  			text3.setText("Known Rituals");
        	  			text4.setText(compileRituals(position));
        	  	break;
        	  	case 5:
        	  		text1.setText("Modifier: " + Draws.modStrings[position]);
            		text2.setText(Draws.modDescriptions[position]);
            		text3.setText("Strategies");
                	text4.setText(Draws.modStrategies[position]);
        	  	break;
        	  	case 6:
        	  		text1.setText("Level: " + Draws.levelStrings[position]);
            		text2.setText(Draws.levelDescriptions[position]);
            		text3.setText("Strategies");
                	text4.setText(Draws.levelStrategies[position]);
        	  	break;
        	  	case 7:
        	  		text1.setText(Draws.creditJobs[position]);
            		text2.setText(Draws.creditBio[position]);
            		text3.setText("");
                	text4.setText("");
        	  	break;
        	  }
        	  
        	  //text1.setTextSize(15+textScaler);
        	  //value.string = text1.toString();
        	  //text1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
        	  //value.string = text2.toString();
        	  //text2.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
        	  //value.string = text3.toString();
        	  //text3.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
        	  //value.string = text4.toString();
        	  //text4.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
          	  //text2.setTextSize((12-(text2.length())/32)+textScaler);
          	  //text3.setTextSize(15+textScaler);
          	  //text4.setTextSize((12-(text4.length())/40)+textScaler);
              //goldcost.setText(""+shopping.returnUpgradeCost(techLevel)[0]);
              //hpotioncost.setText(""+shopping.returnUpgradeCost(techLevel)[1]);
              //mpotioncost.setText(""+shopping.returnUpgradeCost(techLevel)[2]);
              
              //goldstock.setText(""+database.returnTechValues("Gold"));
              //hpotionstock.setText(""+database.returnTechValues("hPotion"));
              //mpotionstock.setText(""+database.returnTechValues("mPotion"));
           }
           public void onNothingSelected(AdapterView<?> arg0) {
        	   // Auto-generated method stub
			
           }
        });
        
        Gallery g2 = (Gallery) findViewById(R.id.shopgalleryTopic);
        g2.setAdapter(new shopImageAdapter(this,R.id.shopgalleryTopic,0));
        ((Gallery) findViewById(R.id.shopgalleryTopic)).setSelection(startingPosition);
        g2.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
           {
        	   ((shopImageAdapter) g1.getAdapter()).setChoice(position);
        	   ((shopImageAdapter) g1.getAdapter()).notifyDataSetChanged();
        	   g1.setSelection(0);
        	   int galleryMover = ((Gallery) findViewById(R.id.shopgallery)).getSelectedItemPosition();
        	   
        	switch(((shopImageAdapter) g1.getAdapter()).returnChoice()){
       	  	case 0:
       		  int techLevel = database.returnTechValues(both[galleryMover]);
       		  ClassShop shopping = new ClassShop(techLevel,galleryMover+1);
       	  
       		  //System.out.println(techLevel + " " + position + "\n");
       		  if (position < 10){
       		  text1.setText(Draws.itemPrefixes[techLevel] 
       				  + " " + both[position]);
       		  }else{
       		  text1.setText(Draws.techPrefixes[techLevel] 
       				  + " " + both[galleryMover]);
       		  }
       		  text2.setText(shopping.printEffectsBuyScreen());
       		  if (techLevel < 9){
           	  shopping = new ClassShop(techLevel+1,galleryMover+1);
           	  if (galleryMover < 10){
           		  text3.setText("Next Level: " + Draws.itemPrefixes[techLevel+1] + " " + both[galleryMover]);
           	  }else{
           		  text3.setText("Next Level: " + Draws.techPrefixes[techLevel+1] + " " + both[galleryMover]);
           	  }
           	  text4.setText(shopping.printEffectsBuyScreen());
       		  }else{
           	  text3.setText("Max Level Reached");
           	  text4.setText("");
       		  }
       		  break;
       	  	case 1:
       	  		if(!unlockAll){
   	  				text1.setText("Class: " + Draws.classStrings[unlock.convertClassPos(galleryMover)]);
   	  				text2.setText(Draws.classDescriptions[unlock.convertClassPos(galleryMover)]);
   	  				text3.setText(Draws.classStrings[unlock.convertClassPos(galleryMover)] + " Strategy");
   	  				text4.setText(Draws.classStrategies[unlock.convertClassPos(galleryMover)]);
   	  			}else{
   	  				text1.setText("Class: " + Draws.classStrings[galleryMover]);
   	  				text2.setText(Draws.classDescriptions[galleryMover]);
   	  				text3.setText(Draws.classStrings[galleryMover] + " Strategy");
   	  				text4.setText(Draws.classStrategies[galleryMover]);
   	  			}

       	  	break;
       	  	case 2:
       	  		if(!unlockAll){
       	  			text1.setText("Enemy: " + Draws.enemyStrings[unlock.convertEnemyPos(galleryMover)]);
       	  			text2.setText(compileEnemyData(unlock.convertEnemyPos(galleryMover)));
       	  			text3.setText("Strategy Against");
       	  			text4.setText(Draws.enemyStrategies[unlock.convertEnemyPos(galleryMover)]);
       		   
       	  		}else{
       	  			text1.setText("Enemy: " + Draws.enemyStrings[galleryMover]);
       	  			text2.setText(compileEnemyData(galleryMover));
       	  			text3.setText("Strategy Against");
       	  			text4.setText(Draws.enemyStrategies[galleryMover]);
       	  		}
       	  	break;
       	  	case 3:
       	  	if(!unlockAll){
       	  		text1.setText("Spell: " + Draws.glyphStrings[unlock.convertGlyphPos(galleryMover)]);
       	  		text2.setText(Draws.glyphDescriptions[unlock.convertGlyphPos(galleryMover)]);
       	  		text3.setText("Spell Strategy");
       	  		text4.setText(Draws.glyphStrategies[unlock.convertGlyphPos(galleryMover)]);
       	  	}else{
       	  		text1.setText("Spell: " + Draws.convertedGlyphNames[galleryMover]);
       	  		text2.setText(Draws.convertedGlyphDescriptions[galleryMover]);
       	  		text3.setText("Spell Strategy");
       	  		text4.setText(Draws.convertedGlyphStrategies[galleryMover]);
       	  	}
       	  		break;
       	  	case 4:
       	  		text1.setText("God: " + Draws.godNames[galleryMover]);
       	  		text2.setText(Draws.godDescriptions[galleryMover] + "\nBlessing: "+Draws.ritualDescriptions[galleryMover][0] +
    				"\nCurse: "+Draws.ritualDescriptions[galleryMover][1]);
     			text3.setText("Known Rituals");
     			text4.setText(compileRituals(galleryMover));
     			break;
       	 case 5:
 	  		text1.setText("Modifier: " + Draws.modStrings[galleryMover]);
     		text2.setText(Draws.modDescriptions[galleryMover]);
     		text3.setText("Strategies");
         	text4.setText(Draws.modStrategies[galleryMover]);
 	  	break;
       	case 6:
	  		text1.setText("Level: " + Draws.levelStrings[galleryMover]);
    		text2.setText(Draws.levelDescriptions[galleryMover]);
    		text3.setText("Strategies");
        	text4.setText(Draws.levelStrategies[galleryMover]);
	  	break;
       	case 7:
	  		text1.setText(Draws.creditJobs[galleryMover]);
    		text2.setText(Draws.creditBio[galleryMover]);
    		text3.setText("");
        	text4.setText("");
	  	break;
       	  }
          //text1.setTextSize(15+textScaler);
      	  //text2.setTextSize((12-(text2.length())/32)+textScaler);
      	  //text3.setTextSize(15+textScaler);
      	  //text4.setTextSize((12-(text4.length())/40)+textScaler);
          //value.string = text1.toString();
      	  //text1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
      	  //value.string = text2.toString();
      	  //text2.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
      	  //value.string = text3.toString();
      	  //text3.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
      	  //value.string = text4.toString();
      	  //text4.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
           }
           public void onNothingSelected(AdapterView<?> arg0) {
        	   // Auto-generated method stub
			
           }
           
        });
        
        final Button button2 = (Button) findViewById(R.id.menu_button);
        
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if (playerStats != null){
            		if(!unlockAll){
            			/*ActivityDungeons.newGame(playerStats.player_race, 
            					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
            					unlock.getLevel()+1);*/
            			finish();
            		}else{
            			//ActivityDungeons.newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
            			finish();
            		}
            	}else{
            		//ActivityDungeons.newGame(0,0,unlock.getLevel()+1);
            		finish();
            	}
            }
        });
        Thread background = new Thread (new Runnable() {
            public void run() {
                    try {
                        while (progress.getProgress()<= max) {
                            Thread.sleep(50);
      
                            // increment the progress bar by 1
                            progress.incrementProgressBy(1);
                        }
                    } catch (java.lang.InterruptedException e) {
                        // if something fails do something smart
                    }
                }
             });
            
            background.start();
        
	}
	
	public class shopImageAdapter extends BaseAdapter {
        /** The parent context */
        private Context myContext;
        private int myview;
        public int choice;
        
        
        /** Simple Constructor saving the 'parent' context. */
        public shopImageAdapter(Context c, int v, int choice) { this.myContext = c; this.myview = v; this.choice = choice;}
 
        public void setChoice(int choice){
        	this.choice = choice;
        }
        
        public int returnChoice(){
        	return this.choice;
        }
        /** Returns the amount of images we have defined. */
        public int getCount() { 
        	
        	//View vg = getCurrentFocus().findFocus();
        	//System.out.println(this.getView(0, null, null));
        	//this.getView(0, null, null);
        	switch(myview){
        		case R.id.shopgallery: 
        			switch(this.choice){
        				case 0: return Draws.shopImages.length;
        				case 1: 
        	        		if (!unlockAll){
        	        			return unlock.returnClassCount();
        	        		}else{
        	        			return Draws.classImages.length;
        	        		}
        				case 2: 
        					if (!unlockAll){
        	        			return unlock.getMonsterCount();
        	        		}else{
        	        			return Draws.enemyImages.length;
        	        		}
        				case 3: 
        					if(!unlockAll){
        						return unlock.returnGlyphCount();
        					}
        					else{
        						return Draws.convertedGlyphImages.length;
        					}
        				case 4: return Draws.godImages.length;
        				case 5: return Draws.modImages.length;
        				case 6: 
        					if (!unlockAll){
        	        			return unlock.returnLevelCount();
        	        		}else{
        	        			return Draws.levelImages.length;
        	        		}
        				case 7: return Draws.creditImages.length;
        				default:return Draws.shopImages.length;
        			}
        		case R.id.shopgalleryTopic: return Draws.helpTopics.length; 
        		default: return Draws.shopImages.length;
        	}
        	
        }
        
        /* Use the array-Positions as unique IDs */
        public Object getItem(int position) { return position; }
        //Returns the positions of the items selected
        public long getItemId(int position) { return position; }
        
        /** Returns a new ImageView to
         * be displayed, depending on
         * the position passed. */
        public View getView(int position, View convertView, ViewGroup parent) {
        	//Display display = getWindowManager().getDefaultDisplay();
            /*ImageView i = new ImageView(this.myContext);
 
            i.setImageResource(this.myImageIds[position]);
            //Image should be scaled as width/height are set.
            //i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setScaleType(ImageView.ScaleType.FIT_START);
            //Set the Width/Height of the ImageView.
            i.setLayoutParams(new Gallery.LayoutParams(75, 75));
            return i;*/
            
        	//View w = getCurrentFocus();
        	//System.out.println(parent);
        	//System.out.println((Gallery) findViewById(R.id.gallery1));
        	
            View v;
            //RelativeLayout borderImg = new RelativeLayout(myContext);

			// just a simple optimiztaion -
			// we only inflate a new layout if we don't have one to reuse

			if (convertView == null)
				v = LayoutInflater.from(this.myContext).inflate(R.layout.imgdesc,
					parent, false);
			else
				v = convertView;
			
			// Now that we have our new custom View, find out widgets in the
			// view and set them
			ImageView iv = (ImageView) v.findViewById(R.id.imageview); 
			
			switch(myview){
    		case R.id.shopgallery: 
    			switch(this.choice){
    				case 0: iv.setImageResource(Draws.shopImages[position]); break; 
    				case 1: 
    					if (!unlockAll){
    						iv.setImageResource(unlock.returnUnlockedClasses()[position]);
    					}else
    					{
    						iv.setImageResource(Draws.classImages[position]); 
    						//iv.setImageBitmap(dScaler[0].graphicScaled[position]);
    					}
    					break;
    				case 2: 
    					if (!unlockAll){
    						iv.setImageResource(unlock.getMonsterImages()[position]);
    					}else
    					{
    						iv.setImageResource(Draws.enemyImages[position]); 
    					}
    					break;
    				case 3:
    					if (!unlockAll){
							iv.setImageResource(unlock.getGlyphImages()[position]);
						}else
						{
							iv.setImageResource(Draws.convertedGlyphImages[position]); 
						}
    					break;
    				case 4: iv.setImageResource(Draws.godImages[position]); break;
    				case 5: iv.setImageResource(Draws.modImages[position]); break;
    				case 6: iv.setImageResource(Draws.levelImages[position]); break;
    				case 7: iv.setImageResource(Draws.creditImages[position]); break;
    				default: iv.setImageResource(Draws.shopImages[position]); break;
    			}
    			break;
    		case R.id.shopgalleryTopic: iv.setImageResource(Draws.helpImages[position]);break; 
    		default: break;
    	}
			
			if(myview == (R.id.shopgalleryTopic)){
				//borderImg.setPadding(1,1,1,1);
            	//borderImg.setBackgroundColor(0xffffff);
            	//borderImg.addView(iv);
			
				//This adds the text underneath the pictures. Removed because it is distracting
			
				TextView tv = (TextView) v.findViewById(R.id.textview);
				
				tv.setText(Draws.helpTopics[position]);

			}
			int multiple = 20 + (int)Math.pow((int)(((float)point.x)/240),2)*22;
			v.setLayoutParams(new Gallery.LayoutParams(multiple, 75));
			if(point.x<360){
				iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			}else{
				iv.setScaleType(ImageView.ScaleType.FIT_START);
			}
			
			return v;
             

            
        }
 
        /** Returns the size (0.0f to 1.0f) of the views
         * depending on the 'offset' to the center. */
        public float getScale(boolean focused, int offset) {
                /* Formula: 1 / (2 ^ offset) */
        return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
        }
    }
}
